package com.ruoyi.auth.controller;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.auth.form.Code;
import com.ruoyi.auth.service.SysLoginService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * 微信登录
 *
 * @author wangsong
 * @date 2019年6月18日 下午8:04:15
 */
@Controller
@RequestMapping("/wx")
public class WeCatController {


    @Autowired
    private RedisService redisService;

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private TokenService tokenService;


    /**
     * 微信登录页
     */
    @GetMapping("/wxLogin")
    public String login() {
        return "wxLogin";
    }

    /**
     * pc点击微信登录，生成登录二维码
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/wxLoginPage", method = RequestMethod.POST)
    @ResponseBody
    public R wxLoginPage(HttpServletRequest request) throws Exception {

        String sessionId = request.getSession().getId();
        // 设置redirect_uri和state=sessionId以及测试号信息，返回授权url
        String uri = sysLoginService.getAuthorizationUrl("pc", sessionId);
        Map<String, String> data = new HashMap<String, String>();
        data.put("sessionId", sessionId);
        // 用来前端生成二维码
        data.put("uri", uri);
        // 生成二维码清除上一个用户的数据
        return R.ok(data);
    }

    /**
     * 扫描二维码授权成功，取到code，设置的回调方法
     *
     * @param code
     * @param state
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/pcAuth")
    public void pcCallback(String code, String state, HttpServletRequest request, HttpServletResponse response,
                           HttpSession session) throws Exception {
        // 根据code获取access_token和openId
        String result = sysLoginService.getAccessToken(code);
        JSONObject jsonObject = JSONObject.parseObject(result, JSONObject.class);
        // String refresh_token = jsonObject.getString("refresh_token");
        String access_token = jsonObject.getString("access_token");
        String openId = jsonObject.getString("openId");

        int complete = 0;
//        查询用户信息
        if (openId != null) {
            LoginUser userInfo = sysLoginService.weixinPclogin(openId, access_token);
            if (!userInfo.getSysUser().getUserType().equals("00")) {
                complete = 1;
            }
            /*生成token*/
            Map<String, Object> token = tokenService.createToken(userInfo);
            redisService.setCacheObject(code, token, 360L, TimeUnit.MINUTES);
            response.setHeader("Authorization", (String) token.get("access_token"));
        }

        response.sendRedirect("http://120.46.220.152/#/pages/login/logins?complete=" + complete + "&" + "code=" + code);
        // 登录成功保存用户数据
//        return "redirect:http://120.46.220.152/#/pages/login/logins";
    }

    /**
     * 检测登录状态(获取用户信息) 每秒被调用一次，
     * <p>
     * 登录成功，立马得到用户信息返回前台，并取消监听
     *
     * @return
     */
    @RequestMapping(value = "/getInfoJson")
    @ResponseBody
    public R getInfoJson(@RequestBody Code code) {
        Object cache = redisService.getCacheObject(code.getCode());
        if (cache == null) {
            return R.ok("no");
        }
        return R.ok(cache);
    }


}
